package com.example.star.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiBuyNow;
import com.example.star.entity.BuyNow;
import com.example.star.entity.Favorite;
import com.example.star.retrofit.ApiClient;
import com.example.star.view.activity.PerimeterDetailActivity;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BuyNowAdapter extends BaseAdapter {
    private static final String TAG = "BuyNowAdapter";
    private Context context;
    private List<BuyNow> buyNows;
    private String loginPassword;
    private ApiBuyNow apiBuyNow;

    public BuyNowAdapter(Context context, List<BuyNow> buyNows) {
        this.context = context;
        this.buyNows = buyNows;
        // 从 SharedPreferences 中读取登陆密码
        SharedPreferences sharedPreferences = context.getSharedPreferences("user_info", Context.MODE_PRIVATE);
        loginPassword = sharedPreferences.getString("loginPassword", "");

        // 获取 ApiBuyNow 实例
        apiBuyNow = ApiClient.getApiBuyNow();
    }

    @Override
    public int getCount() {
        return buyNows != null ? buyNows.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return buyNows != null ? buyNows.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_buynow, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.imagePerimeter = convertView.findViewById(R.id.image_perimeter);
            viewHolder.perimeterOrders = convertView.findViewById(R.id.perimeter_orders);
            viewHolder.starNameTextView = convertView.findViewById(R.id.star_name);
            viewHolder.perimeterTitleTextView = convertView.findViewById(R.id.perimeter_title);
            viewHolder.priceTextView = convertView.findViewById(R.id.prices);
            viewHolder.totalPriceTextView = convertView.findViewById(R.id.total_price);
            viewHolder.confirmShopping = convertView.findViewById(R.id.confirm_shopping);
            viewHolder.confirmPayment = convertView.findViewById(R.id.confirm_payment);
            viewHolder.goToEvaluate = convertView.findViewById(R.id.go_to_evaluate); // 添加去评价按钮
            viewHolder.finish = convertView.findViewById(R.id.finish);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        BuyNow buyNow = buyNows.get(position);
        loadImage(viewHolder.imagePerimeter, buyNow.getImageResource());
        viewHolder.perimeterOrders.setText(buyNow.getOrderStatus());
        viewHolder.starNameTextView.setText(buyNow.getStarName());
        viewHolder.perimeterTitleTextView.setText(buyNow.getTitle());
        viewHolder.priceTextView.setText(buyNow.getPrices());
        viewHolder.totalPriceTextView.setText(buyNow.getTotalPrice() + "元");

        // 根据订单状态决定显示确认收货，确认付款，去评价
        if ("待收货".equals(buyNow.getOrderStatus())) {
            viewHolder.confirmShopping.setVisibility(View.VISIBLE);
            viewHolder.confirmPayment.setVisibility(View.GONE);
            viewHolder.goToEvaluate.setVisibility(View.GONE);
            viewHolder.finish.setVisibility(View.GONE);
        } else if ("待付款".equals(buyNow.getOrderStatus())) {
            viewHolder.confirmPayment.setVisibility(View.VISIBLE);
            viewHolder.confirmShopping.setVisibility(View.GONE);
            viewHolder.goToEvaluate.setVisibility(View.GONE);
            viewHolder.finish.setVisibility(View.GONE);
        } else if ("待评价".equals(buyNow.getOrderStatus())) {
            viewHolder.goToEvaluate.setVisibility(View.VISIBLE);
            viewHolder.confirmPayment.setVisibility(View.GONE);
            viewHolder.confirmShopping.setVisibility(View.GONE);
            viewHolder.finish.setVisibility(View.GONE);
        } else if ("已完成".equals(buyNow.getOrderStatus())) {
            viewHolder.finish.setVisibility(View.VISIBLE);
            viewHolder.confirmShopping.setVisibility(View.GONE);
            viewHolder.confirmPayment.setVisibility(View.GONE);
            viewHolder.goToEvaluate.setVisibility(View.GONE);
        }

        // 添加点击事件
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, PerimeterDetailActivity.class);
                intent.putExtra("starName", buyNow.getStarName());
                intent.putExtra("perimeterTitle", buyNow.getTitle());
                intent.putExtra("prices", buyNow.getPrices());
                intent.putExtra("imageResource", buyNow.getImageResource());
                intent.putExtra("productType", buyNow.getProductType());
                intent.putExtra("freight", buyNow.getFreight());
                intent.putExtra("deliveryAddress", buyNow.getDeliveryAddress());
                context.startActivity(intent);
            }
        });

        // 添加长按删除事件
        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if ("待付款".equals(buyNow.getOrderStatus()) ||
                        "待评价".equals(buyNow.getOrderStatus()) ||
                        "已完成".equals(buyNow.getOrderStatus())) {
                    // 弹出确认对话框
                    new AlertDialog.Builder(context)
                            .setTitle("删除订单")
                            .setMessage("你确定要删除这个订单吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 发起网络请求删除订单
                                    Call<Void> call = apiBuyNow.deleteOrder(buyNow.getId());
                                    call.enqueue(new Callback<Void>() {
                                        @Override
                                        public void onResponse(Call<Void> call, Response<Void> response) {
                                            if (response.isSuccessful()) {
                                                // 从本地数据中移除订单
                                                buyNows.remove(position);
                                                notifyDataSetChanged();
                                                Toast.makeText(context, "订单已删除", Toast.LENGTH_SHORT).show();
                                            } else {
                                                try {
                                                    String errorMessage = response.errorBody().string();
                                                    Toast.makeText(context, "删除订单失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                                                } catch (Exception e) {
                                                    Toast.makeText(context, "删除订单失败: 未知错误", Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<Void> call, Throwable t) {
                                            Toast.makeText(context, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
                } else {
                    Toast.makeText(context, "当前订单状态不允许删除", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });

        // 确认付款点击事件
        viewHolder.confirmPayment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出输入密码对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("请输入支付密码");
                builder.setMessage("支付金额: " + buyNow.getTotalPrice() + "元");
                final EditText input = new EditText(context);
                builder.setView(input);
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String password = input.getText().toString();
                        // 密码验证逻辑
                        if (password.equals(loginPassword)) {
                            // 更新本地订单状态
                            buyNow.setOrderStatus("待收货");
                            notifyDataSetChanged();

                            // 发起网络请求更新数据库中的订单状态
                            Call<BuyNow> call = apiBuyNow.updateOrderStatus(buyNow.getId(), "待收货");
                            call.enqueue(new Callback<BuyNow>() {
                                @Override
                                public void onResponse(Call<BuyNow> call, Response<BuyNow> response) {
                                    if (response.isSuccessful()) {
                                        Toast.makeText(context, "订单状态已改变，状态：" + buyNow.getOrderStatus(), Toast.LENGTH_SHORT).show();
                                    } else {
                                        try {
                                            String errorMessage = response.errorBody().string();
                                            Toast.makeText(context, "更改订单状态失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                                        } catch (Exception e) {
                                            Toast.makeText(context, "更改订单状态失败: 未知错误", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<BuyNow> call, Throwable t) {
                                    Toast.makeText(context, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            // 密码错误提示
                            new AlertDialog.Builder(context)
                                    .setTitle("密码错误")
                                    .setMessage("请输入正确的登录密码")
                                    .setPositiveButton("确定", null)
                                    .show();
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });

        // 确认收货点击事件
        viewHolder.confirmShopping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出确认对话框
                new AlertDialog.Builder(context)
                        .setTitle("确认收货")
                        .setMessage("你确定要确认收货吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 更新本地订单状态
                                buyNow.setOrderStatus("待评价");
                                notifyDataSetChanged();

                                // 发起网络请求更新数据库中的订单状态
                                Call<BuyNow> call = apiBuyNow.updateOrderStatus(buyNow.getId(), "待评价");
                                call.enqueue(new Callback<BuyNow>() {
                                    @Override
                                    public void onResponse(Call<BuyNow> call, Response<BuyNow> response) {
                                        if (response.isSuccessful()) {
                                            Toast.makeText(context, "订单状态已改变，状态：" + buyNow.getOrderStatus(), Toast.LENGTH_SHORT).show();
                                        } else {
                                            try {
                                                String errorMessage = response.errorBody().string();
                                                Toast.makeText(context, "更改订单状态失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                                            } catch (Exception e) {
                                                Toast.makeText(context, "更改订单状态失败: 未知错误", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<BuyNow> call, Throwable t) {
                                        Toast.makeText(context, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });

        // 去评价点击事件
        viewHolder.goToEvaluate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出评价对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                LayoutInflater inflater = LayoutInflater.from(context);
                View dialogView = inflater.inflate(R.layout.dialog_evaluation, null);
                builder.setView(dialogView);

                RatingBar ratingBar = dialogView.findViewById(R.id.ratingBar);
                EditText commentEditText = dialogView.findViewById(R.id.commentEditText);

                builder.setTitle("商品评价");
                builder.setPositiveButton("提交", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        float rating = ratingBar.getRating();
                        String comment = commentEditText.getText().toString();

                        // 提交评价到服务器
                        Call<String> evaluationCall = apiBuyNow.submitEvaluation(buyNow.getId(), rating, comment);
                        evaluationCall.enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                if (response.isSuccessful()) {
                                    // 更新本地订单状态
                                    buyNow.setOrderStatus("已完成");
                                    notifyDataSetChanged();

                                    // 调用 updateOrderStatus 方法更新服务器端订单状态
                                    Call<BuyNow> statusCall = apiBuyNow.updateOrderStatus(buyNow.getId(), "已完成");
                                    statusCall.enqueue(new Callback<BuyNow>() {
                                        @Override
                                        public void onResponse(Call<BuyNow> call, Response<BuyNow> response) {
                                            if (response.isSuccessful()) {
                                                Toast.makeText(context, "订单状态已改变，状态：" + buyNow.getOrderStatus(), Toast.LENGTH_SHORT).show();
                                            } else {
                                                try {
                                                    String errorMessage = response.errorBody().string();
                                                    Toast.makeText(context, "更新订单状态失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                                                } catch (Exception e) {
                                                    Toast.makeText(context, "更新订单状态失败: 未知错误", Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<BuyNow> call, Throwable t) {
                                            Toast.makeText(context, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } else {
                                    try {
                                        String errorMessage = response.errorBody().string();
                                        Toast.makeText(context, "评价提交失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                                    } catch (Exception e) {
                                        Toast.makeText(context, "评价提交失败: 未知错误", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {
                                Toast.makeText(context, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });

        return convertView;
    }

    private void loadImage(ImageView imageView, String imageResource) {
        if (imageResource != null) {
            try {
                int imageResId = context.getResources().getIdentifier(imageResource, "drawable", context.getPackageName());
                if (imageResId != 0) {
                    imageView.setImageResource(imageResId);
                } else {
                    Glide.with(context)
                            .load(imageResource)
                            .placeholder(R.drawable.register)
                            .error(R.drawable.register)
                            .into(imageView);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error loading image: " + e.getMessage());
                Glide.with(context)
                        .load(imageResource)
                        .placeholder(R.drawable.register)
                        .error(R.drawable.register)
                        .into(imageView);
            }
        }
    }

    private static class ViewHolder {
        ImageView imagePerimeter;
        TextView perimeterOrders;
        TextView starNameTextView;
        TextView perimeterTitleTextView;
        TextView priceTextView;
        TextView totalPriceTextView;
        TextView confirmShopping;
        TextView confirmPayment;
        TextView goToEvaluate; // 添加去评价按钮
        TextView finish;
    }

    public void clear() {
        buyNows.clear();
        notifyDataSetChanged();
    }
}